# -*- encoding: utf-8 -*-
from openerp.osv import fields,osv
from openerp.addons.dm_base import utils

class mrp_bom(osv.osv):
    _inherit = 'mrp.bom'
    def _update_bom_oper(self, cr, uid, bom_id, context=None):
        if context == None:
            context = {}
        ctx = context.copy()
        ctx['active_test'] = False
        bom = self.browse(cr, uid, bom_id, context=ctx)
        if not bom.bom_id:
            #成品工艺路线模板
            routing_template_id = None
            if not bom.routing_template_id:
                #自动设置成品&半成品物料清单的工艺路线模板
                routing_template_id = None
                if bom.product_id.default_code[6:7] == '1':
                    #半成品
                    routing_template_id = 2520
                else:
                    #成品
                    routing_template_id = 2521
                self.write(cr, uid, [bom_id], {'routing_template_id':routing_template_id}, context=context)
            else:
                routing_template_id = bom.routing_template_id.id
            #部件工序
            for line in bom.bom_lines:
                oper_ids = []
                if line.routing_template_workcenter_ids:
                    #检查部件工序的工艺路线是否是成品的工艺路线模板下面的工序
                    oper_ids = [oper.id for oper in line.routing_template_workcenter_ids  if oper.routing_id.id == routing_template_id]
                    oper_ids_remove = [oper.id for oper in line.routing_template_workcenter_ids  if oper.routing_id.id != routing_template_id]
                    if oper_ids and oper_ids_remove:
                        #删除部分不应该设置的工序
                        self.write(cr, uid, [line.id], {'routing_template_workcenter_ids':[[6, False, oper_ids]]}, context=context)
                if not oper_ids:
                    #增加产品设置的,成品的工艺路线模板下面的工序
                    oper_ids = [oper.id for oper in line.product_id.routing_template_workcenter_ids if oper.routing_id.id == routing_template_id]
                    self.write(cr, uid, [line.id], {'routing_template_workcenter_ids':[[6, False, oper_ids]]}, context=context)    
    def create(self, cr, uid, vals, context=None):
        bom_id = super(mrp_bom,self).create(cr, uid, vals, context=context)
        self._update_bom_oper(cr, uid, bom_id, context=context)
        return bom_id
    def to_state(self,cr,uid,ids,new_state,context=None):
        if new_state == 'review':
            for bom_id in ids:
                self._update_bom_oper(cr, uid, bom_id, context=context)
        return super(mrp_bom, self).to_state(cr, uid, ids, new_state, context=context)    
            
